package com.software.myopiachildren.ui;


import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jaeger.library.StatusBarUtil;
import com.king.zxing.CaptureActivity;
import com.king.zxing.ViewfinderView;
import com.software.myopiachildren.MainActivity;
import com.software.myopiachildren.R;
import com.software.myopiachildren.base.BaseActivity;
import com.software.myopiachildren.bean.BaseInfo;
import com.software.myopiachildren.content.Constant;
import com.software.myopiachildren.http.HostType;
import com.software.myopiachildren.http.HttpApi2;
import com.software.myopiachildren.utils.AndroidWorkaround;
import com.software.myopiachildren.utils.ToastUtil;
import com.software.myopiachildren.utils.eb.EB;
import com.software.myopiachildren.utils.eb.EbData;
import com.software.myopiachildren.utils.perm.NetworkUtils;
import com.software.myopiachildren.utils.sp.SP;
import com.software.myopiachildren.view.dialog.CustomizeDialog;
import com.yanzhenjie.permission.Action;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;

import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;


/**
 * 扫描绑定设备页
 *
 * @author penglei
 * @date 2020/05/14
 */
public class ScanBindActivity extends CaptureActivity {
    private static final String TAG = "ScanBindActivity";

    @BindView(R.id.iv_title_left)
    ImageView mIvTitleLeft;
    @BindView(R.id.tv_title_text)
    TextView mTvTitleText;
    @BindView(R.id.tv_title_right)
    TextView mTvTitleRight;
    @BindView(R.id.lay_title_home)
    LinearLayout mLayTitleHome;

    @BindView(R.id.tv_input)
    TextView mTvInput;

    @BindView(R.id.surfaceView)
    SurfaceView mSurfaceView;
    @BindView(R.id.viewfinderView)
    ViewfinderView mViewfinderView;
    @BindView(R.id.ivTorch)
    ImageView mIvTorch;


    @Override
    public int getLayoutId() {
        StatusBarUtil.setTransparent(this);
        StatusBarUtil.setLightMode(this); // 设置app状态栏字体颜色（黑色）
        return R.layout.activity_scan_bind;
    }

    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        ButterKnife.bind(this);
        //适配虚拟按键
        if (AndroidWorkaround.checkDeviceHasNavigationBar(this)) {
            AndroidWorkaround.assistActivity(findViewById(android.R.id.content));
        }
        getCaptureHelper()
//                .decodeFormats(DecodeFormatManager.QR_CODE_FORMATS)//设置只识别二维码会提升速度
                .playBeep(true)
                .vibrate(true);

        initView();
        initData();
        getPermissions();
    }

    public void initView() {
        mTvTitleText.setText(getResources().getString(R.string.s_bind_device));

        // 设置扫描框参数

    }


    public void initData() {

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onPause() {
        super.onPause();
    }


    @OnClick({R.id.iv_title_left, R.id.tv_input})
    public void onClick(final View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.iv_title_left:
                finish();
                break;

            case R.id.tv_input:
                inputDeviceDialog();
                break;
        }
    }

    private void getPermissions() {
        AndPermission.with(this)
                .permission(Permission.CAMERA, Permission.READ_EXTERNAL_STORAGE)
                .onGranted(new Action() {
                    @Override
                    public void onAction(List<String> permissions) {
//                        Toast.makeText(MainActivity.this, "没有权限", Toast.LENGTH_LONG).show();
                    }
                })
                .onDenied(new Action() {
                    @Override
                    public void onAction(List<String> permissions) {
                        Uri packageURI = Uri.parse("package:" + getPackageName());
                        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI);
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);
//                        Toast.makeText(MainActivity.this, "", Toast.LENGTH_LONG).show();
                        ToastUtil.showShort("没有权限无法扫描呦");
                    }
                }).start();
    }

    /**
     * 手动输入设备号弹框
     */
    private void inputDeviceDialog() {
        final CustomizeDialog dialog = new CustomizeDialog(ScanBindActivity.this, R.style.DialogUtilStyle);
        dialog.setOnShowListener(new DialogInterface.OnShowListener() {
            @Override
            public void onShow(DialogInterface dialogInterface) {
                EditText et_bind_input = (EditText) dialog.findViewById(R.id.et_bind_input);
                Button btn_confirm = (Button) dialog.findViewById(R.id.btn_confirm);
                ImageView iv_close = (ImageView) dialog.findViewById(R.id.iv_close);

                //取消
                iv_close.setOnClickListener(v -> {
                    dialog.dismiss();
                });

                //确认
                btn_confirm.setOnClickListener(v -> {
                    String deviceNum = et_bind_input.getText().toString().trim();
                    //验证设备号
                    if (TextUtils.isEmpty(deviceNum)) {
                        ToastUtil.showShort(getString(R.string.toast_devicenum_empty));
                        return;
                    }
                    getBindDevice(deviceNum);
                    dialog.dismiss();
                });
            }
        });
        dialog.showDialog(R.layout.dialog_bind_device);
    }


    /**
     * 绑定设备
     */
    private void getBindDevice(String device_code) {
        String jwt_token = new SP().load(Constant.USER_JWT_TOKEN, "");
        if (NetworkUtils.isConnected(ScanBindActivity.this)) {
            Map<String, String> headers = new HashMap<>();
            headers.put("Authorization", jwt_token);

            Map<String, String> params = new HashMap<>();
            params.put("device_code", device_code);

            HttpApi2.getApiService(HostType.TELE_CONFIG).getBindDevice(headers, params).subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Subscriber<BaseInfo>() {
                        @Override
                        public void onSubscribe(Subscription s) {
                            s.request(Long.MAX_VALUE);
                        }

                        @Override
                        public void onNext(BaseInfo baseInfo) {
                            try {
                                Log.e(TAG, "===baseInfo:" + baseInfo.toString());
                                if (baseInfo.getCode().equals(Constant.CODE_SUCCESS)) {
                                    ToastUtil.showShort(baseInfo.getMsg());
                                    EB.post(new EbData(10));
                                    finish();
                                } else {
                                    ToastUtil.showShort(baseInfo.getMsg());
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }

                        @Override
                        public void onError(Throwable t) {

                        }

                        @Override
                        public void onComplete() {

                        }
                    });
        } else {
            ToastUtil.showShort(getResources().getString(R.string.network_fial_message));
        }
    }

}
